﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace sfsocket.corelib.message
{
    /// <summary>
    /// length  - 
    /// type    - 0x00000006 broadcast message 
    /// msg     - msg string 
    /// </summary>
    public class ChatMessage : BaseMessage
    {
        private string m_chatmsg;

        public string Chatmsg
        {
            get { return m_chatmsg; }
            set { m_chatmsg = value; }
        }

        public ChatMessage()
        {

        }

        public ChatMessage(string _msg)
        {
            this.MessageType = (int)MessageTypeEnum.BROADCAST;
            this.m_chatmsg = _msg;
            this.Length = 4 + _msg.Length;
        }

        public void Parse(byte[] _buff, int offset, int length)
        {
            Stream memStream = new MemoryStream(_buff, offset, length);
            BinaryReader reader = new BinaryReader(memStream);
            this.Chatmsg = Encoding.ASCII.GetString(reader.ReadBytes(length));
        }

        public static ChatMessage Parse(byte[] _headerBuf)
        {
            if (_headerBuf == null)
                return null;

            ChatMessage msg = new ChatMessage();

            Stream memStream = new MemoryStream(_headerBuf);
            BinaryReader reader = new BinaryReader(memStream);

            msg.Length = IPAddress.NetworkToHostOrder(reader.ReadInt32());

            // validate the packet 
            if (msg.Length != _headerBuf.Length - 4)
            {
                msg = null;
                throw new ArgumentException("invalid packet! length is not valid!");
            }

            msg.MessageType = IPAddress.NetworkToHostOrder(reader.ReadInt32());
            msg.Chatmsg = Encoding.ASCII.GetString(reader.ReadBytes(msg.Length - 4));

            return msg;
        }

        public override byte[] GetBytes()
        {
            byte[] buff = new byte[Length + 4];
            Stream memStream = new MemoryStream(buff);
            BinaryWriter writer = new BinaryWriter(memStream);
            writer.Write(IPAddress.HostToNetworkOrder(Length));
            writer.Write(IPAddress.HostToNetworkOrder(MessageType));
            writer.Write(Encoding.ASCII.GetBytes(Chatmsg));
            writer.Close();
            memStream.Close();
            return buff;
        }


        public class ChatMessageUnitTest
        {
            public static void Test()
            {
                Console.WriteLine("Test");

                // 1) contruct from raw packet 

                BaseMessage fmsg2 = new ChatMessage();
                fmsg2.Dump();
                fmsg2.DumpHex();


            }
        }
    }
}
